//
//  ZZSearchChooseController.m
//  QQplayground
//
//  Created by zhangxy on 2018/7/5.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZSearchChooseController.h"
#import "ZTextField.h"
#import "ZZHomeTopMenu.h"
#import "ZZShareView.h"


#import "UIView+Extension.h"
#import "ZZChannelCell.h"

#import "ZZChannelLabel.h"
static NSString * const reuseID  = @"ZZChannelCell";

@interface ZZSearchChooseController ()<UITextFieldDelegate,UICollectionViewDelegate, UICollectionViewDataSource,UIGestureRecognizerDelegate>{
    
}

/** 当前要展示频道 */
@property (nonatomic, strong) NSMutableArray *list_now; // 功能待完善
/** 频道列表 */
@property (nonatomic, strong) UIScrollView *smallScrollView;
/** 新闻视图 */
@property (nonatomic, strong) UICollectionView *bigCollectionView;
/** 下划线 */
@property (nonatomic, strong) UIView *underline;


@property(nonatomic,strong) ZTextField *searchField;

@end

@implementation ZZSearchChooseController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationBar];
    
    [self createSearchController];
    
    
    
    _list_now = [[NSMutableArray alloc] init];
    [_list_now addObjectsFromArray:@[@"素材",@"帖子",@"用户"]];
    
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, NavBarHeight, ScreenWidth, 44)];
    [imgView setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    [self.view addSubview:imgView];
    
    [self.view addSubview:self.smallScrollView];
    [self.view addSubview:self.bigCollectionView];
    
}


#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 输出点击的view的类名
    NSLog(@"%@", NSStringFromClass([touch.view class]));
    
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        
        return NO;
    }
    return  YES;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}




#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _list_now.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZZChannelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
    
    // 1、素材 2、帖子， 3 用户
    [cell searchNav:indexPath.row + 1 search:convertToString(_searchField.text)];
    // 如果不加入响应者链，则无法利用NavController进行Push/Pop等操作。
    [self addChildViewController:(UIViewController *)cell.newsTVC];
    return cell;
}


#pragma mark - UICollectionViewDelegate
/** 正在滚动 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat value = scrollView.contentOffset.x / scrollView.frame.size.width;
    if (value < 0) {return;} // 防止在最左侧的时候，再滑，下划线位置会偏移，颜色渐变会混乱。
    
    NSUInteger leftIndex = (int)value;
    NSUInteger rightIndex = leftIndex + 1;
    if (rightIndex >= [self getLabelArrayFromSubviews].count) {  // 防止滑到最右，再滑，数组越界，从而崩溃
        rightIndex = [self getLabelArrayFromSubviews].count - 1;
    }
    
    CGFloat scaleRight = value - leftIndex;
    CGFloat scaleLeft  = 1 - scaleRight;
    
    ZZChannelLabel *labelLeft  = [self getLabelArrayFromSubviews][leftIndex];
    ZZChannelLabel *labelRight = [self getLabelArrayFromSubviews][rightIndex];
    
    labelLeft.scale  = scaleLeft;
    labelRight.scale = scaleRight;
    
    //     NSLog(@"value = %f leftIndex = %zd, rightIndex = %zd", value, leftIndex, rightIndex);
    //     NSLog(@"左%f 右%f", scaleLeft, scaleRight);
    //     NSLog(@"左：%@ 右：%@", labelLeft.text, labelRight.text);
    
    // 点击label会调用此方法1次，会导致【scrollViewDidEndScrollingAnimation】方法中的动画失效，这时直接return。
    if (scaleLeft == 1 && scaleRight == 0) {
        return;
    }
    
    // 下划线动态跟随滚动：马勒戈壁的可算让我算出来了
    _underline.centerX = labelLeft.centerX   + (labelRight.centerX   - labelLeft.centerX)   * scaleRight;
    _underline.width   = labelLeft.textWidth + (labelRight.textWidth - labelLeft.textWidth) * scaleRight;
}

/** 手指滑动BigCollectionView，滑动结束后调用 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:self.bigCollectionView]) {
        [self scrollViewDidEndScrollingAnimation:scrollView];
    }
}

/** 手指点击smallScrollView */
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    // 获得索引
    NSUInteger index = scrollView.contentOffset.x / self.bigCollectionView.width;
    // 滚动标题栏到中间位置
    ZZChannelLabel *titleLable = [self getLabelArrayFromSubviews][index];
    CGFloat offsetx   =  titleLable.center.x - _smallScrollView.width * 0.5;
    CGFloat offsetMax = _smallScrollView.contentSize.width - _smallScrollView.width;
    // 在最左和最右时，标签没必要滚动到中间位置。
    if (offsetx < 0)         {offsetx = 0;}
    if (offsetx > offsetMax) {offsetx = offsetMax;}
    [_smallScrollView setContentOffset:CGPointMake(offsetx, 0) animated:YES];
    
    // 先把之前着色的去色：（快速滑动会导致有些文字颜色深浅不一，点击label会导致之前的标题不变回黑色）
    for (ZZChannelLabel *label in [self getLabelArrayFromSubviews]) {
        label.textColor = UIColorFromRGB(TextWhiteColor);
    }
    // 下划线滚动并着色
    [UIView animateWithDuration:0.5 animations:^{
        self.underline.width = titleLable.textWidth;
        self.underline.centerX = titleLable.centerX;
        titleLable.textColor = UIColorFromRGB(TextWhiteColor);
    }];
}




#pragma mark - getter

- (UIScrollView *)smallScrollView
{
    if (_smallScrollView == nil) {
        _smallScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(20, NavBarHeight, ScreenWidth-40,44)];
        _smallScrollView.backgroundColor = [UIColor clearColor];
        _smallScrollView.showsHorizontalScrollIndicator = NO;
        // 设置频道
        [self setupChannelLabel];
        // 设置下划线
        [_smallScrollView addSubview:({
            ZZChannelLabel *firstLabel = [self getLabelArrayFromSubviews][0];
            firstLabel.textColor = [UIColor whiteColor];
            // smallScrollView高度44，取下面4个点的高度为下划线的高度。
            _underline = [[UIView alloc] initWithFrame:CGRectMake(0, 38, firstLabel.textWidth, 2)];
            _underline.centerX = firstLabel.centerX;
            _underline.backgroundColor = [UIColor whiteColor];
            _underline.layer.cornerRadius = 2.0f;
            _underline.layer.masksToBounds = YES;
            _underline;
        })];
    }
    return _smallScrollView;
}

- (UICollectionView *)bigCollectionView
{
    if (_bigCollectionView == nil) {
        // 高度 = 屏幕高度 - 导航栏高度64 - 频道视图高度44
        CGFloat h = ScreenHeight - NavBarHeight - 44;
        CGRect frame = CGRectMake(0, self.smallScrollView.maxY, ScreenWidth, h);
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _bigCollectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
        _bigCollectionView.backgroundColor = [UIColor clearColor];
        _bigCollectionView.delegate = self;
        _bigCollectionView.dataSource = self;
        
        [_bigCollectionView registerClass:[ZZChannelCell class] forCellWithReuseIdentifier:reuseID];
        
        // 设置cell的大小和细节
        flowLayout.itemSize = _bigCollectionView.bounds.size;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        _bigCollectionView.pagingEnabled = YES;
        _bigCollectionView.showsHorizontalScrollIndicator = NO;
    }
    return _bigCollectionView;
}



#pragma mark -
/** 设置频道标题 */
- (void)setupChannelLabel
{
    CGFloat margin = 20.0;
    CGFloat h = _smallScrollView.bounds.size.height;
   
    
    for (int i = 0;i<_list_now.count;i++) {
        ZZChannelLabel *label = [ZZChannelLabel channelLabelWithTitle:_list_now[i]];
        CGFloat mx = (ScreenWidth - (label.width + margin) * 3 - margin * 3 - 90)/2;
        [label setTextColor:UIColorFromRGB(TextWhiteColor)];
        label.frame = CGRectMake(45 + label.width * i + margin*i + mx * i, 0, label.width + margin, h);
        
        [_smallScrollView addSubview:label];
        
        label.tag = i;
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick:)]];
    }
    _smallScrollView.contentSize = CGSizeMake(ScreenWidth - 40, 0);
}

/** 频道Label点击事件 */
- (void)labelClick:(UITapGestureRecognizer *)recognizer
{
    ZZChannelLabel *label = (ZZChannelLabel *)recognizer.view;
    // 点击label后，让bigCollectionView滚到对应位置。
    [_bigCollectionView setContentOffset:CGPointMake(label.tag * _bigCollectionView.frame.size.width, 0)];
    // 重新调用一下滚定停止方法，让label的着色和下划线到正确的位置。
    [self scrollViewDidEndScrollingAnimation:self.bigCollectionView];
}

/** 获取smallScrollView中所有的DDChannelLabel，合成一个数组，因为smallScrollView.subViews中有其他非Label元素 */
- (NSArray *)getLabelArrayFromSubviews
{
    NSMutableArray *arrayM = [NSMutableArray array];
    for (ZZChannelLabel *label in _smallScrollView.subviews) {
        if ([label isKindOfClass:[ZZChannelLabel class]]) {
            [arrayM addObject:label];
        }
    }
    return arrayM.copy;
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

#pragma mark 搜索视图
- (void)createSearchController
{
    //在tableView存在右侧索引情况下防止搜索框右侧缺少一块
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, ScreenWidth, NavBarHeight);
    [headerView setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    
    _searchField = [[ZTextField alloc] initWithImage:[UIImage imageNamed:@"搜索 copy"] padding:5];
    [_searchField setPlaceholder:Uninput_search];
    [_searchField setFrame:CGRectMake(20, StatusBarHeight, ScreenWidth - 64, 44)];
    [_searchField setBackgroundColor:UIColor.whiteColor];
    _searchField.layer.cornerRadius = 10.0f;
    _searchField.layer.masksToBounds = YES;
    _searchField.clearsOnBeginEditing = YES;
    _searchField.returnKeyType = UIReturnKeySearch;
    _searchField.delegate = self;
    [_searchField addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
    [headerView addSubview:_searchField];
    
    [self.view addSubview:headerView];
    
    
    UIButton *btnSearch = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnSearch setImage:[UIImage imageNamed:@"搜索 关闭"] forState:0];
    [btnSearch setFrame:CGRectMake(ScreenWidth - 44, StatusBarHeight, 44, 44)];
    btnSearch.tag = 1;
    [btnSearch addTarget:self action:@selector(actionBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnSearch];
}


#pragma mark - 搜索
/*
 每次输入文字都会进行搜索，但只有点击确认之后，才会写入搜索历史
 */
- (void)textFieldValueChanged:(UITextField *)textField
{
    DLog(@"text:%@",textField.text);
    if (textField.text.length > 0) {
//        [self searchAction];
    }
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self searchAction];
    return YES;
}

- (void)searchAction
{
    [_searchField resignFirstResponder];
    
    if (_searchField.text.length == 0) {
        return;
    }
    
    [self.bigCollectionView reloadData];
    
}

-(void)actionBack{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
